<template>
  <main class="w-full flex">
    <NcCompBlogSidebar
      :documents="docs"
      class="hidden lg:block lg:w-1/5 Container"
    ></NcCompBlogSidebar>
    <NcCompBlogContent
      v-if="doc"
      :doc="doc"
      :prev="prev"
      :next="next"
      class="w-full lg:w-4/5 Container bg-white dark:bg-gray-900 z-10"
    ></NcCompBlogContent>
    <NcCompBlogList v-else :docs="docs"></NcCompBlogList>
  </main>
</template>

<script>
import NcCompBlogSidebar from '@/components/blog-comp/NcCompBlogSidebar'
import NcCompBlogContent from '@/components/blog-comp/NcCompBlogContent'
import NcCompBlogList from '@/components/blog-comp/NcCompBlogList'

export default {
  name: 'NcBlogPage',
  layout: 'NcBlogLayout',
  components: { NcCompBlogList, NcCompBlogContent, NcCompBlogSidebar },

  async asyncData({ $content, store, app, params, error, $i18n }) {
    let docs
    try {
      docs = await $content(app.i18n.locale, params.pathMatch || 'index', {
        deep: true,
      })
        .where({ private: { $ne: true } })
        .sortBy('position', 'asc')
        .fetch()
    } catch (e) {
      return error({ statusCode: 404, message: 'Page not found!' })
    }

    // console.log({ 'path match': params.pathMatch })
    // console.log({ 'type of docs': Object.prototype.toString.call(docs) })

    if (docs.length === 0) {
      return error({ statusCode: 404, message: '正在开发，敬请期待！' })
    } else if (Object.prototype.toString.call(docs) === '[object Object]') {
      const doc = docs

      const scope = params.pathMatch.split('/')[0]
      docs = await $content(app.i18n.locale, scope, { deep: true })
        .where({ private: { $ne: true } })
        .sortBy('position', 'asc')
        .fetch()
      const [prev, next] = await $content(app.i18n.locale, { deep: true })
        .where({ private: { $ne: true } })
        .without('body')
        .sortBy('uniDirPath')
        .sortBy('position')
        .surround(doc.slug)
        .fetch()

      // console.log({ doc, prev, next })

      return {
        docs,
        doc,
        prev,
        next,
      }
    } else {
      return {
        doc: null,
        docs,
      }
    }
  },
  methods: {},
}
</script>
